#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("五子棋");
    this->setWindowState(Qt::WindowMaximized);
    InitStyle();
    InitOnce();
    getLocalIP();
    if(menu.exec()==QDialog::Accepted)
    {
        switch(MenuDialog::GAMEMODE)
        {
        case RobotPk:InitRobotPk();
            break;
        case NetworkPk:InitNetworkPk();
            break;
        case DoublePk:InitDoublePk();
            break;
        }
        this->show();
    }
    else
        exit(0);

}
void Widget::InitStyle()
{
    QFile file("../GoBang/MainStyle.qss");
    if(!file.open(QIODevice::ReadOnly))
        qDebug()<<"MainStyle.qss open failed!";
    QString style = file.readAll();
    file.close();
    this->setStyleSheet(style);

    //QFontDatabase::addApplicationFont(":/new/font/Alimama_DongFangDaKai_Regular.ttf"); //Alimama DongFangDaKai
}

void Widget::InitOnce()
{
    tcpSocket = new QTcpSocket(this);
    //双人对战
    CountDownTimer_me = new QTimer(this);
    connect(CountDownTimer_me,&QTimer::timeout,[=]()    //我方计时器倒计时
    {
        Me_remain_time--;
        if(Me_remain_time == -1)    //白棋倒计时结束,黑棋胜利
        {
            emit ui->widget_board->signal_whiteTimeout();
            return;
        }
        int m = Me_remain_time/60;
        int s = Me_remain_time%60;
        ui->myTime->setText(QString("倒计时:%1:%2").arg(m).arg(s));

    });

    CountDownTimer_enemy = new QTimer(this);
    connect(CountDownTimer_enemy,&QTimer::timeout,[=]() //对手计时器倒计时
    {
        Enemy_remain_time--;
        if(Enemy_remain_time == -1)    //黑棋倒计时结束,白棋胜利
        {
            emit ui->widget_board->signal_blackTimeout();
            return;
        }
        int m = Enemy_remain_time/60;
        int s = Enemy_remain_time%60;
        ui->enemyTime->setText(QString("倒计时:%1:%2").arg(m).arg(s));
    });

    connect(ui->widget_board,&ChessBoard::signal_timerChange,[=]()  //一方落子后计时器交替运行
    {
        if(CountDownTimer_me->isActive())
        {
            CountDownTimer_me->stop();
            CountDownTimer_enemy->start();
        }else{
            CountDownTimer_me->start();
            CountDownTimer_enemy->stop();
        }
    });

    connect(ui->widget_board,&ChessBoard::signal_gameover,[=]() //游戏结束重新初始化
    {
        Me_remain_time = 900;
        Enemy_remain_time = 900;
        ui->myTime->setText(QString("倒计时:15:00"));
        ui->enemyTime->setText(QString("倒计时:15:00"));
        CountDownTimer_me->start();
        CountDownTimer_enemy->stop();
    });

}

void Widget::InitRobotPk()
{
    ui->stackedWidget_me->setCurrentWidget(ui->page_double);
    ui->stackedWidget_enemy->setCurrentWidget(ui->page_double_2);
    emit ui->widget_board->signal_GameMode(RobotPk);
}

void Widget::InitNetworkPk()
{
    ui->stackedWidget_me->setCurrentWidget(ui->page_networkPk);
    ui->stackedWidget_enemy->setCurrentWidget(ui->page_networkPk_2);
    emit ui->widget_board->signal_GameMode(NetworkPk);

    //连接服务器
    tcpSocket->connectToHost(QHostAddress("10.16.16.35"),ClientPort);
    connect(tcpSocket,&QTcpSocket::readyRead,[=]()
    {
        //获取消息类型
        QString message = tcpSocket->readAll();
        QString type = message.section('#',0,0);
        switch(type.toInt())
        {
        case ChatInfo:      //聊天消息
        {

        }
            break;
        case MatchInfo:     //匹配消息
        {
            //类型#消息#颜色
            QString data = message.section('#',1,1);
            QString color = message.section('#',-1,-1);
            ui->plainTextEdit->clear();
            ChatText = "\n" + data;
            ui->plainTextEdit->setPlainText(ChatText);
            ui->widget_board->setChessColor(color.toInt());
        }
            break;
        case ChessInfo:     //落子信息
        {
            //类型#颜色#x坐标#y坐标
            int color = message.section('#',1,1).toInt();
            int x = message.section('#',2,2).toInt();
            int y = message.section('#',3,3).toInt();
            emit ui->widget_board->signal_recevePeerChess(color,QPoint(x,y));
        }
            break;
        case WinInfo:       //胜利消息
        {
            int color = message.section('#',1,1).toInt();
            emit ui->widget_board->signal_receveWin(color);
        }
            break;
        }



    });
    type = Match;       //状态变更为匹配中
    //阻塞主线程,显示匹配中字样,将该主机添加到服务器的匹配池中
    //类型#本机IP
    QString data = QString("%1#%2").arg(MatchInfo).arg(LocalIP);
    tcpSocket->write(data.toUtf8());
    if(type == Match)
    {
        ChatText += "正在匹配中...";
        ui->plainTextEdit->appendPlainText(ChatText);
    }

    connect(ui->widget_board,&ChessBoard::signal_chesspos,[=](int type,QPoint pos)  //向服务器发送落子的信息
    {
        //落子信息类型#颜色#x坐标#y坐标
        QString data = QString("%1#%2#%3#%4")
                .arg(ChessInfo).arg(type).arg(pos.x()).arg(pos.y());
        tcpSocket->write(data.toUtf8());
    });

    connect(ui->widget_board,&ChessBoard::signal_win,[=](int color)     //某一方胜利消息
    {
        //胜利消息类型#颜色
        QString data = QString("%1#%2").arg(WinInfo).arg(color);
        tcpSocket->write(data.toUtf8());
    });
}

void Widget::InitDoublePk()
{
    ui->stackedWidget_me->setCurrentWidget(ui->page_double);
    ui->stackedWidget_enemy->setCurrentWidget(ui->page_double_2);
    emit ui->widget_board->signal_GameMode(DoublePk);

    //15分钟 = 900s
    Me_remain_time = 900;
    Enemy_remain_time = 900;
    ui->myTime->setText(QString("倒计时:15:00"));
    ui->enemyTime->setText(QString("倒计时:15:00"));
    CountDownTimer_me->start(1000); //直接开始游戏
    CountDownTimer_enemy->start(1000);
    CountDownTimer_enemy->stop();

    emit ui->widget_board->signal_clearBoard();
}

void Widget::getLocalIP()
{
    QString ip_address;
       QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // 获取所有ip
       for (int i = 0; i < ipAddressesList.size(); ++i)
       {

           QHostAddress ipAddr = ipAddressesList.at(i);
           if ((ipAddr.protocol() == QAbstractSocket::IPv4Protocol))// 筛选出ipv4
           {
               if (!ipAddr.toString().startsWith("169"))// 过滤掉网卡，路由器等的ip
               {
                   ip_address = ipAddr.toString();
                   break;
               }
           }
       }
       if (ip_address.isEmpty())
           ip_address = QHostAddress(QHostAddress::LocalHost).toString();
        LocalIP = ip_address;
}

Widget::~Widget()
{
    delete ui;
}

//返回
void Widget::on_btn_backup_clicked()
{
    this->close();
    if(menu.exec()==QDialog::Accepted)
    {
        switch(MenuDialog::GAMEMODE)
        {
        case RobotPk:InitRobotPk();
            break;
        case NetworkPk:InitNetworkPk();
            break;
        case DoublePk:InitDoublePk();
            break;
        }
        this->show();
    }
    else
        exit(0);
}

//离开
void Widget::on_btn_exit_clicked()
{
    on_btn_backup_clicked();
}

//发送消息
void Widget::on_btn_send_clicked()
{
    QString str = ui->lineEdit->text();
    ui->lineEdit->clear();
    //数据打包序列化  类型#本机IP#数据
    QString data = QString("%1#%2#%3").arg(ChatInfo).arg(LocalIP).arg(str);
    //发送给服务器
    tcpSocket->write(data.toUtf8());
}

